package beautiful.butterfly.drds.binlog.handlers;


import beautiful.butterfly.drds.binlog.connection.ConnectionAttributes;
import beautiful.butterfly.drds.binlog.connection.ConnectionFactory;
import beautiful.butterfly.drds.binlog.netty.server.NioSocketChannelExtend;
import beautiful.butterfly.drds.binlog.operation.OpeationEvent;
import beautiful.butterfly.drds.binlog.operation.OpeationEventQueue;
import beautiful.butterfly.drds.binlog.operation.OperationType;
import beautiful.butterfly.drds.binlog.utils.Constants;
import beautiful.butterfly.drds.binlog.utils.StringUtils;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ServiceChannelInitializer extends ChannelInitializer<SocketChannel>
{


    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception
    {
        // 要在这里加上所有的处理句柄
        log.info("initChannel invoked...");
        //LoggerUtils.debug(logger, "channel:" + channel.getClass().toGenericString());
        log.info("channel:" + socketChannel.getClass().getCanonicalName());
        ChannelPipeline channelPipeline = socketChannel.pipeline();// 下面的次序不能变
        channelPipeline.addLast(Constants.FIXED_LENGTH_HANDLER, new FixedLengthChannelInboundHandler());
        channelPipeline.addLast(Constants.GREETING_PACKET_HANDLER, new GreetingPacketResultChannelInboundHandler());
        channelPipeline.addLast(Constants.AUTHEN_RESULT_HANDLER, new AuthenticateResultChannelInboundHandler());
        channelPipeline.addLast(Constants.FETCH_BINLOG_NAMEPOSITION_RESULT_HANDLER, new FetchBinlogNamePositionResultChannelInboundHandler());
        channelPipeline.addLast(Constants.FETCH_BINLOG_CHECKSUM_RESULT_HANDLER, new FetchBinlogCheckSumResultChannelInboundHandler());
        channelPipeline.addLast(Constants.LOG_EVENT_PARSE_HANDLER, new BinlogEventParseChannelInboundHandler());
        channelPipeline.addLast(Constants.CHANNEL_TRIGGER_DE_REGISTERED, new ChannelDeRegisterChannelInboundHandler());
        // 到这里就可以存起来
        NioSocketChannelExtend nioSocketChannelExtend = (NioSocketChannelExtend) socketChannel;
        ConnectionAttributes connectionAttributes = nioSocketChannelExtend.getConnectionAttributes();
        String ip = connectionAttributes.getIp();//这里是IP数组，没问题
        int port = connectionAttributes.getPort();
        ConnectionFactory.put(StringUtils.union(ip, "" + port), nioSocketChannelExtend);
        // 发送一个消息给OperationServer,告诉它当前机器新增了一个连接
        // 放入队列就闪
        OpeationEventQueue.addObject(new OpeationEvent(null, OperationType.socket_add));
        log.info("send a socket_add message to operation queue");
        // 启动此socketChannel的任务线程
        connectionAttributes.startTaskThread();
    }

}
